package com.luboyan.CBillbill.controller;

import com.alibaba.fastjson.JSONObject;
import com.luboyan.CBillbill.dao.file.*;
import com.luboyan.CBillbill.dao.vo.PageVo;
import com.luboyan.CBillbill.service.elasticsearch.ElasticSearchService;
import com.luboyan.CBillbill.service.file.DanmuService;
import com.luboyan.CBillbill.service.file.VideoService;
import com.luboyan.CBillbill.util.Result;
import com.luboyan.CBillbill.advice.TokenVerify;
import org.apache.mahout.cf.taste.common.TasteException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 视频投稿功能
 */
@RestController
@RequestMapping("files")
public class VideoController {

    @Autowired
    private VideoService videoService;

    @Autowired
    private DanmuService danmuService;

    @Autowired
    private ElasticSearchService elasticSearchService;

    @Autowired
    private TokenVerify tokenVerify;

    /**
     * 新增视频
     */
    @PostMapping("/videos")
    public Result<String> addVideos(@RequestBody Video video) {
        Long userId = tokenVerify.getCurrentUserId();
        video.setUserId(userId);
        videoService.addVideos(video);
        elasticSearchService.addVideo(video);
        return Result.success();
    }

    /**
     * 根据分区分页返回视频
     */
    @GetMapping("/videos")
    public Result<PageVo<Video>> pageVoVideos(Integer page, Integer pageSize, String area) {
        PageVo<Video> result = videoService.pageVoVideos(page, pageSize, area);
        return new Result<>(result);
    }

    /**
     * 获取所有视频分页返回
     */
    @GetMapping("/test/videos")
    public Result<PageVo<Video>> getVideos(Integer page, Integer pageSize){
        PageVo<Video> result = videoService.pageVoAllVideos(page, pageSize);
        return new Result<>(result);
    }

    /**
     * 分片下载视频,通过流进行传输
     */
    @GetMapping("/videos-shard")
    public void getVideosByShard(HttpServletRequest request,
                                 HttpServletResponse response,
                                 String path) throws Exception {

        videoService.getVideosByShard(request, response, path);
    }

    /***
     * 查询标签
     */
    @GetMapping("/tags")
    public Result<ArrayList<Tag>> getTags(){
        ArrayList<Tag> tagList= videoService.getTags();
        return new Result<>(tagList);
    }

    /**
     * 点赞视频
     */
    @PostMapping("/videos-like")
    public Result<String> addVideoLike(@RequestParam Long videoId) {
        Long userId = tokenVerify.getCurrentUserId();
        videoService.addVideoLike(videoId, userId);
        return Result.success();
    }

    /**
     * 取消点赞
     */
    @DeleteMapping("/videos-like")
    public Result<String> deleteVideoLike(@RequestParam Long videoId) {
        Long userId = tokenVerify.getCurrentUserId();
        videoService.deleteVideoLike(videoId, userId);
        return Result.success();
    }

    /**
     * 查询视频点赞
     */
    @GetMapping("/videos-like")
    public Result<Map<String, Object>> getVideoLikes(@RequestParam Long videoId) {
        Long userId = null;
        try {
            userId = tokenVerify.getCurrentUserId();
        } catch (Exception ignored) {
        }
        Map<String, Object> result = videoService.getVideoLikes(videoId, userId);
        return new Result<>(result);
    }

    /**
     * 收藏视频
     */
    @PostMapping("/video-collections")
    public Result<String> addVideoCollections(@RequestBody VideoCollection videoCollection) {
        Long userId = tokenVerify.getCurrentUserId();
        videoService.addVideoCollections(videoCollection, userId);
        return Result.success();
    }

    /**
     * 取消收藏
     */
    @DeleteMapping("/video-collections")
    public Result<String> deleteVideoCollections(@RequestParam Long videoId) {
        Long userId = tokenVerify.getCurrentUserId();
        videoService.deleteVideoCollections(videoId, userId);
        return Result.success();
    }

    /**
     * 获取视频收藏量
     */
    @GetMapping("/video-collections")
    public Result<Map<String, Object>> getVideoCollections(@RequestParam Long videoId) {
        Long userId = null;
        try {
            userId = tokenVerify.getCurrentUserId();
        } catch (Exception ignored) {
        }
        Map<String, Object> result = videoService.getVideoCollections(videoId, userId);
        return new Result<>(result);
    }

    /**
     * 用户添加视频关注分组
     */
    @PostMapping("/video-collections-groups")
    public Result<Long> addVideoCollectionGroup(@RequestBody CollectionGroup collectionGroup) {
        Long userId = tokenVerify.getCurrentUserId();
        collectionGroup.setUserId(userId);
        Long groupId = videoService.addUserFollowingGroups(collectionGroup);
        return new Result<>(groupId);
    }

    /**
     * 用户获取视频关注分组
     */
    @GetMapping("/collections-groups")
    public Result<List<CollectionGroup>> getVideoCollectionGroup() {
        Long userId = tokenVerify.getCurrentUserId();
        List<CollectionGroup> result = videoService.getVideoCollectionGroup(userId);
        return new Result<>(result);
    }

    /**
     * 得到收藏视频
     *
     * @return 以分组的形式返回给前端
     */
    @GetMapping("/video-collections-groups")
    public Result<PageVo<Video>> PageVideoCollectionGroup(@RequestParam Integer page,
                                                          @RequestParam Integer pageSize,
                                                          @RequestParam(required = false, defaultValue = "1") Long groupId) {
        Long userId = tokenVerify.getCurrentUserId();
        PageVo<Video> result = videoService.PageVideoCollectionGroup(page, pageSize, userId, groupId);
        return new Result<>(result);
    }

    /**
     * 用户给视频进行投币
     */
    @PostMapping("/video-coins")
    public Result<String> addVideoCoins(@RequestBody VideoCoin videoCoin) {
        Long userId = tokenVerify.getCurrentUserId();
        videoService.addVideoCoins(videoCoin, userId);
        return Result.success();
    }

    /**
     * 获取视频投币量
     */
    @GetMapping("/video-coins")
    public Result<Map<String, Object>> getVideoCoins(@RequestParam Long videoId) {
        Long userId = null;
        try {
            userId = tokenVerify.getCurrentUserId();
        } catch (Exception ignored) {
        }
        Map<String, Object> result = videoService.getVideoCoins(videoId, userId);
        return new Result<>(result);
    }

    /**
     * 添加视频评论
     */
    @PostMapping("/video-comments")
    public Result<String> addVideoComments(@RequestBody VideoComment videoComment) {
        Long userId = tokenVerify.getCurrentUserId();
        videoService.addVideoComments(videoComment, userId);
        return Result.success();
    }

    /**
     * 查询视频评论
     */
    @GetMapping("/video-comments")
    public Result<PageVo<VideoComment>> PageGetVideoComments(@RequestParam Integer page,
                                                             @RequestParam Integer pageSize,
                                                             @RequestParam Long videoId) {
        PageVo<VideoComment> result = videoService.PageGetVideoComments(page, pageSize, videoId);
        return new Result<>(result);
    }

    /**
     * 获取视频详情
     */
    @GetMapping("/video-details")
    public Result<Map<String, Object>> getVideoDetails(@RequestParam Long videoId) {
        Map<String, Object> result = videoService.getVideoDetails(videoId);
        return new Result<>(result);
    }

    /**
     * 获取视频弹幕
     */
    @GetMapping("/videos-danmus")
    public Result<List<Danmu>> getDanmus(@RequestParam Long videoId,
                                         String startTime, String endTime) throws Exception {
        List<Danmu> result;
        JSONObject params = new JSONObject();
        params.put("videoId", videoId);
        try {
            tokenVerify.getCurrentUserId();
            result = danmuService.getDanmus(videoId, startTime, endTime);
        } catch (Exception ignored) {
            result = danmuService.getDanmus(videoId, null, null);
        }
        return new Result<>(result);
    }


    /**
     * 添加视频观看记录
     */
    @PostMapping("/videos-views")
    public Result<String> addVideoView(@RequestBody VideoView videoView,
                                       HttpServletRequest request) {
        Long userId = null;
        try {
            userId = tokenVerify.getCurrentUserId();
            videoView.setUserId(userId);
            videoService.addVideoView(videoView, request);
        } catch (Exception ignored) {
            videoService.addVideoView(videoView, request);
        }
        return Result.success();
    }

    /**
     * 查询视频播放量
     */
    @GetMapping("/videos-views")
    public Result<Integer> getVideoViewCounts() {
        Long userId = tokenVerify.getCurrentUserId();
        Integer result = videoService.getVideoViewCounts(userId);
        return new Result<>(result);
    }

    /**
     * 查询视频播放记录
     */

    /**
     * 视频推荐（基于用户）
     */
    @GetMapping("/recommendations")
    public Result<List<Video>> recommend() throws TasteException {
        Long userId = tokenVerify.getCurrentUserId();
        List<Video> result = videoService.recommend(userId);;
        return new Result<>(result);
    }

    //一些待完善的：视频标签的crud（放在UserController里）；移动视频收藏分组；删除一个分组后，分组下的视频怎么处理？视频的标签添加，编辑，删除；用户
    //注册时的硬币数；视频评论还可以用闭包表树形结构，评论添加赞和踩功能；推送自己视频的相关消息；获取视频详情的完善；
}
